package com.atguigu.gulimall.cart.interceptor;

import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.to.MemberTo;
import com.atguigu.gulimall.cart.vo.UserInfoVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 购物车拦截器
 *
 * @author DuGuanghan
 * @since 2025-02-14 10:52:13
 */
public class CartInterceptor implements HandlerInterceptor {
    public static ThreadLocal<UserInfoVo> threadLocal = new ThreadLocal<>();

    /**
     * 在请求之前执行
     *
     * @param request  请求
     * @param response 响应
     * @param handler  处理器
     * @return boolean
     * @author DuGuanghan
     * @since 2025-02-14 10:53:10
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取HttpSession的JSESSIONID信息
        HttpSession session = request.getSession();
        MemberTo jsessionid = (MemberTo) session.getAttribute("loginUser");

        UserInfoVo userInfoVo = new UserInfoVo();
        if (jsessionid != null) {
            // 若用户已登录，则将用户ID设置到UserInfoVo中
            userInfoVo.setUserId(jsessionid.getId());
        }

        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                // 若用户未登录，则从Cookie中查询用户的临时信息
                if (CartConstant.TEMP_USER_COOKIE_NAME.equals(cookie.getName())) {
                    userInfoVo.setUserKey(cookie.getValue());
                    userInfoVo.setTempUser(true);
                }
            }
        }

        if (StringUtils.isBlank(userInfoVo.getUserKey())) {
            // 若用户未登录，则生成一个临时用户信息
            String uuid = UUID.randomUUID().toString();
            userInfoVo.setUserKey(uuid);
        }

        // 调用ThreadLocal，在同一次请求中将用户信息存储到ThreadLocal中
        threadLocal.set(userInfoVo);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 将TreadLocal保存在cookie中，通过response响应返回给浏览器
        UserInfoVo userInfoVo = threadLocal.get();

        // 若不是临时用户，则创建一个临时用户，并保存到cookie中
        if (!userInfoVo.isTempUser()) {
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoVo.getUserKey());
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            cookie.setDomain("gulimall.com");

            response.addCookie(cookie);
        }
    }
}
